import 'package:aidou/controller/videoListController.dart';
import 'package:aidou/main.dart';
import 'package:aidou/pages/live/index.dart';
import 'package:aidou/pages/livebroadcast.dart';
import 'package:aidou/pages/login/index.dart';
import 'package:aidou/pages/message.dart';
import 'package:aidou/pages/mine.dart';
import 'package:aidou/widgets/video/page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class MyHomePage extends StatefulWidget {
  @override
  createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _currentIndex = 0;
  List<Widget> _pageList = [
    HomeScreen(key: homeKey),
    LivebroadcastScreen(),
    MessageScreen(),
    MineScreen(),
  ];

  @override
  Widget build(BuildContext context) {
    //设置尺寸（填写设计中设备的屏幕尺寸）如果设计基于360dp * 690dp的屏幕
    ScreenUtil.init(
      context,
      designSize: Size(750, 1334),
      minTextAdapt: true,
      // orientation: Orientation.portrait,
    );

    return Scaffold(
      body: Stack(
        children:
            _pageList.asMap().keys.map((e) => buildPageOffstage(e)).toList(),
      ),
      bottomNavigationBar: _buildBottomNavigationBar(),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }

  Widget buildPageOffstage(int e) {
    return new Offstage(
      offstage: this._currentIndex > 2
          ? this._currentIndex != (e + 1)
          : this._currentIndex != e,
      child: _pageList[e],
    );
  }

  // 底部tab
  Widget _buildBottomNavigationBar() {
    return Container(
      color: Colors.black,
      child: SafeArea(
        child: SizedBox(
          height: 48.0,
          child: Card(
            color: this._currentIndex == 0
                ? Colors.black.withOpacity(0.5)
                : Colors.white,
            elevation: 0.0,
            shape: RoundedRectangleBorder(),
            margin: EdgeInsets.all(0.0),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                _buildBottomItem(title: '首页', index: 0),
                _buildBottomItem(title: '直播', index: 1),
                _buildBottomItem(title: '发布', index: 2),
                _buildBottomItem(title: '消息', index: 3),
                _buildBottomItem(title: '我的', index: 4)
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildBottomItem({required String title, required int index}) {
    Color _colors = index == _currentIndex
        ? (_currentIndex == 0 ? Colors.white : Colors.black)
        : (_currentIndex == 0 ? Colors.grey.shade400 : Colors.grey);

    return Expanded(
      child: InkResponse(
        highlightColor: Colors.black,
        radius: 0.0,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            title == '发布'
                ? Icon(
                    Icons.add_box,
                    size: 32,
                    color: _currentIndex == 0 ? Colors.white : Colors.black,
                  )
                : Text(
                    title,
                    style: TextStyle(
                      color: _colors,
                      fontSize: 16.0,
                      fontWeight: FontWeight.w600,
                    ),
                  )
          ],
        ),
        onTap: () {
          if (index == 2) {
            Navigator.of(context).push(
              MaterialPageRoute(builder: (context) {
                return LoginPage();
                // return LivePage();
              }),
            );
            return;
          }
          setState(() {
            _currentIndex = index;
          });
          homeKey.currentState?.videoControllerPause(index == 0);
        },
      ),
    );
  }
}

// 通过GlobalKey调用子组件方法
GlobalKey<_HomeScreenState> homeKey = GlobalKey();

// 首页
class HomeScreen extends StatefulWidget {
  HomeScreen({
    Key? key,
  }) : super(key: key);
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen>
    with SingleTickerProviderStateMixin, RouteAware {
  List<String> tabTextList = ['推荐', '关注'];
  List<Tab> tabWidgetList = [];
  TabController? tabController;
  // 推荐数据
  int currentTabIndex = 0;

  List<VideoListController> videoController = [
    VideoListController(),
    VideoListController()
  ];
  // List<VideoData> videoDataList = [];

  @override
  void initState() {
    for (var item in tabTextList) {
      tabWidgetList.add(
        Tab(text: '$item'),
      );
    }
    // tab控制器
    tabController = new TabController(length: tabTextList.length, vsync: this);
    // 监听tab当前屏，判断暂停播放视频
    tabController?.addListener(() {
      final int? value = tabController?.index;
      setState(() {
        currentTabIndex = value!;
      });
      if (videoController[this.currentTabIndex].playerList.length > 0) {
        videoController[this.currentTabIndex].currentPlayer.play();
      }
      var index = value == 1 ? 0 : 1;
      if (videoController[index].playerList.length > 0) {
        videoController[index].currentPlayer.pause();
      }
    });

    super.initState();
  }

  @override
  void didChangeDependencies() {
    routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
    super.didChangeDependencies();
  }

  // 点击底部导航栏时，判断暂停视频播放
  void videoControllerPause(bool flag) {
    var controller = videoController[this.currentTabIndex];
    if (flag) {
      controller.currentPlayer.play();
    } else {
      controller.currentPlayer.pause();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Positioned(
            left: 0.0,
            right: 0.0,
            top: 0.0,
            bottom: 0.0,
            child: Container(
              color: Colors.black,
            ),
          ),
          Positioned(
            left: 0.0,
            right: 0.0,
            top: 0.0,
            bottom: 0.0,
            child: BuildTableViewWidget(
              tabController: tabController,
              tabTextList: tabTextList,
              currentTabIndex: currentTabIndex,
              videoController: videoController,
            ),
          ),
          Positioned(
            left: 0.0,
            right: 0.0,
            top: 24.0,
            bottom: 0.0,
            child: buildTabBarWidget(),
          ),
        ],
      ),
    );
  }

  // tabbar
  buildTabBarWidget() {
    return Container(
      // 对齐在顶部中间
      alignment: Alignment.topCenter,
      child: new TabBar(
        controller: tabController,
        tabs: tabWidgetList,
        // 指示器的颜色
        indicatorColor: Colors.white,
        // 指示器高度
        indicatorWeight: 2,
        // 指示器间距
        indicatorPadding: EdgeInsets.only(bottom: 2.0),
        isScrollable: true,
        // 指示器的宽度与文字对齐
        indicatorSize: TabBarIndicatorSize.label,
      ),
    );
  }

  @override
  void didPush() {
    print('打开页面时，该方法调起');
  }

  @override
  void didPushNext() {
    print('push到下一个页面时，该方法调起');
    this.videoControllerPause(false);
  }

  @override
  void didPop() {
    print('当前页面关闭时，该方法调起');
  }

  @override
  void didPopNext() {
    print('路由pop回到页面时，该方法调起');
    this.videoControllerPause(true);
  }
}

// tabview部件，添加监听是否进入后台运行
class BuildTableViewWidget extends StatefulWidget {
  final TabController? tabController;
  final List<String> tabTextList;
  final int currentTabIndex;
  final List<VideoListController> videoController;
  const BuildTableViewWidget({
    Key? key,
    this.tabController,
    required this.tabTextList,
    required this.currentTabIndex,
    required this.videoController,
  }) : super(key: key);

  @override
  _BuildTableViewWidgetState createState() => _BuildTableViewWidgetState();
}

class _BuildTableViewWidgetState extends State<BuildTableViewWidget>
    with WidgetsBindingObserver {
  @override
  void initState() {
    // 添加观察者
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }

  // APP生命周期改变回调
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    super.didChangeAppLifecycleState(state);
    print(state);
    if (state == AppLifecycleState.paused) {
      // app退到后台后, 刷新状态
      // widget.videoController.currentPlayer.pause();
    }
    // app显示后，刷新状态
    if (state != AppLifecycleState.resumed) {
      // 刷新代码
      widget.videoController[widget.currentTabIndex].currentPlayer.pause();
    } else {
      widget.videoController[widget.currentTabIndex].currentPlayer.play();
    }
  }

  @override
  void dispose() {
    // 移除观察者
    WidgetsBinding.instance.removeObserver(this);
    // widget.videoController.currentPlayer.pause();
    widget.videoController[widget.currentTabIndex].dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new TabBarView(
      controller: widget.tabController,
      children: widget.tabTextList
          .map((value) => buildTableViewItemWidget(value))
          .toList(),
    );
  }

  // 上下滑动的页面
  Widget buildTableViewItemWidget(String value) {
    return VideoPlayerPage(
      value: value,
      videoController:
          value == '推荐' ? widget.videoController[0] : widget.videoController[1],
    );
  }
}
